const mongoose = require('mongoose');
const Message = require('../models/message.js');
require('dotenv').config();

class DatabaseService {
    constructor() {
        this.uri = process.env.MONGODB_URI;
    }

    async connect() {
        try {
            await mongoose.connect(this.uri, {
                useNewUrlParser: true,
                useUnifiedTopology: true,
            });
            console.log('成功连接到MongoDB');
        } catch (error) {
            console.error('MongoDB连接错误:', error);
            process.exit(1);
        }
    }

    async save(data) {
        try {
            const message = new Message(data);
            const savedMessage = await message.save(data);
            console.log('消息已保存到数据库:', savedMessage._id);
            return savedMessage;
        } catch (error) {
            console.error('保存消息时出错:', error);
            throw error;
        }
    }
}

module.exports = new DatabaseService();
